package com.elt.protocol.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.elt.protocol.inter.IProtocol;
import com.elt.protocol.util.PojoMapConverter;
import com.elt.util.CheckUtil;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class XMLProtocolImpl implements IProtocol {
	private XStream xstreamList = new XStream(new DomDriver());
	private XStream xstreamMap = new XStream(new DomDriver());

	public XMLProtocolImpl() {
		// TODO Auto-generated constructor stub
		xstreamList.registerConverter(new PojoMapConverter());
	}

	@Override
	public String fromMap(Map<String, Object> map) {
		// TODO Auto-generated method stub
		return xstreamMap.toXML(map);
	}

	@Override
	public Map<String, Object> toMap(String data) {
		// TODO Auto-generated method stub
		if (!CheckUtil.isNotNullString(data)) {
			return null;
		}

		Object result = xstreamMap.fromXML(data);
		if (!(result instanceof Map)) {
			throw new UnsupportedClassVersionError();
		}
		return (Map<String, Object>) result;
	}

	@Override
	public List<Map<String, Object>> toList(String data) {
		// TODO Auto-generated method stub

		if (!CheckUtil.isNotNullString(data)) {
			return null;
		}

		ArrayList<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		xstreamList.alias("data", Map.class);

		Map<String, Object> map = (Map<String, Object>) xstreamList
				.fromXML(data);

		if (map.size() != 0) {
			Object obj = map.get("body");

			if (obj == null || "".equals(obj)) {
				return resultList;
			}

			if (obj instanceof Map) {

				Object item = ((Map<String, Object>) obj).get("itembody");

				if (item != null) {
					resultList.add((Map<String, Object>) item);
				} else {
					resultList.add((Map<String, Object>) obj);
				}

			}
			if (obj instanceof List) {
				resultList.addAll((ArrayList<Map<String, Object>>) obj);
			} else {
				resultList.clear();
			}

		}
		return resultList;
	}

}
